package com.ly.mpayment.rest.up.xuanjie;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("xuanjie")
public class XuanJieRest {
    Logger logger = Logger.getLogger(XuanJieRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @Path("callBack")
    @POST
    public String callBack(@RequestBody String data) {
        logger.info("xuanjie_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            //szVerifyString=md5(szAgentId=xxx&szOrderId=xxx&szPhoneNum=xxx&nDemo=xxx&fSalePrice=xxx&nFlag=xxx&szKey=xxx) .ToLower()
            MultiMap multiMap = Util.parceString(data);
            UpOrder order = upOrderService.findById(multiMap.getString("szOrderId"));
            if(order == null){
                logger.info("订单不存在:"+data);
                return "订单不存在";
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+data);
                return "failt";
            }

            //szVerifyString=md5(szAgentId=xxx&szOrderId=xxx&szPhoneNum=xxx&nDemo=xxx&fSalePrice=xxx&nFlag=xxx&szKey=xxx) .ToLower()
            if(!multiMap.getString("szVerifyString").equals(MD5.md5("szAgentId="+upShopInfo.getAppId()+"&szOrderId="+order.getUporderuuid()+
                    "&szPhoneNum="+multiMap.getString("szPhoneNum")+"&nDemo="+multiMap.getString("nDemo")+"&fSalePrice="+multiMap.getString("fSalePrice")
                    +"&nFlag="+multiMap.getString("nFlag")+"&szKey="+upShopInfo.getUpkey()).toLowerCase())){
                logger.info("签名错误:"+data);
                return "failt";
            }

            if (order != null && multiMap.getString("nFlag").equals("2") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("szRtnMsg") ? multiMap.getString("szRtnMsg") : multiMap.getString("nFlag"));
                RechargeRest.successUpOrder.add(order);
                return "ok";
            } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("nFlag").equals("3")) {
                order.setRemark(multiMap.getString("nFlag"));
                RechargeRest.failtUpOrder.add(order);
                return "ok";
            } else {
                this.upOrderService.addOrderMsg(order,multiMap.getString("nFlag"));
                logger.info("xuanjie_not_found_order:" + multiMap.getString("tel") + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        return "0";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("szAgentId", shop.getAppId());
        data.put("szOrderId", order.getUporderuuid());
        data.put("szPhoneNum", order.getUpphonenum());
        data.put("nMoney", order.getUpShopPro().getUpfacevalue());
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("nSortType", order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "1" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "2" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "3" : 4);
        data.put("nProductClass", 1);
        data.put("nProductType", 1);
        data.put("szNotifyUrl", shop.getOrderCallAddress());
        data.put("szTimeStamp", DateUtils.getNowDateToString());
        //sign=md5(mchid+tel+price+orderid+teltype+timeout+notify+time+rand+商户秘钥)
        data.put("szVerifyString", MD5.md5("szAgentId="+
                data.getString("szAgentId") +"&szOrderId="+
                data.getString("szOrderId") +"&szPhoneNum="+
                data.getString("szPhoneNum") +"&nMoney="+
                data.getString("nMoney") +"&nSortType="+
                data.getString("nSortType") +"&nProductClass="+
                data.getString("nProductClass") +"&nProductType="+
                data.getString("nProductType") +"&szTimeStamp="+
                data.getString("szTimeStamp")
                        .concat("&szKey="+shop.getUpkey())).toLowerCase());
        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress(), StringSort.jsonToString(data));
        logger.info("commitOrder_xuanjie:" + result + ":" + StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("nRtn") && json.getString("nRtn").equals("0")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getString("szOrderId"),json.containsKey("szRtnCode") ?
                            json.getString("szRtnCode") : "");
                } else if (json.containsKey("nRtn") && errorCode.contains(json.getString("nRtn"))){
                    order.setRemark(json.getString("szRtnCode"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, json.getString("szRtnCode"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrder(order, "");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("1000");
        add("1001");
        add("1003");
        add("1004");
        add("2001");
        add("2002");
        add("2003");
        add("2020");
        add("2021");
        add("1006");
        add("2030");
    }};

    /**
     * 订单查询
     *
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        JSONObject data = new JSONObject();
        data.put("szOrderId", upOrder.getUporderuuid());
        data.put("szAgentId", shopInfo.getAppId());
        data.put("szVerifyString", MD5.md5("szAgentId="+
                data.getString("szAgentId") +"&szOrderId="+
                data.getString("szOrderId")
                        .concat("&szKey="+shopInfo.getUpkey())).toLowerCase());
        String result = HttpClient.postUrlFrom(shopInfo.getOrderStatusAddress(), StringSort.jsonToString(data));
        logger.info("xuanjiequeryOrder:" + StringSort.jsonToString(data) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            //{"szOrderId":"2c99e0237941a983017941aa1f5d0004","fSalePrice":47.7,"nRtn":5013,"szRtnCode":"fail","szRtnMsg":""}
            JSONObject jsonD = JSONObject.parseObject(result);
            if (jsonD.containsKey("nRtn") ) {
                UpOrder order = upOrderService.findById(jsonD.getString("szOrderId"));
                if (order != null && jsonD.getString("nRtn").equals("5012") && order.getStatus() == Config.status[0]) {
                    order.setRemark( jsonD.containsKey("szRtnMsg") ? jsonD.getString("szRtnMsg") :
                            jsonD.containsKey("szRtnCode") ? jsonD.getString("szRtnCode") : "");
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("nRtn").equals("5013") ) {
                    order.setRemark( jsonD.containsKey("szRtnCode") ? jsonD.getString("szRtnCode") : "");
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    this.upOrderService.addOrderMsg(order,jsonD.getString("szRtnCode"));
                    logger.info("xuanjie_not_found_order:" + order.getUpphonenum());
                }
            } else {
                logger.info("xuanjie_not_found_order:" + upOrder.getUpphonenum());
            }
        }
    }
}
